package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lhh
 * @ClassName HouseBrokerController
 * @date 2022/9/19 11:36
 */

@Controller
@RequestMapping("houseBroker")
public class HouseBrokerController {

    @Reference
    private AdminService adminService;

    @Reference
    private HouseBrokerService houseBrokerService;

    @GetMapping("create")
    public String findAll(Model model, @RequestParam("houseId") Long houseId){
        List<Admin> adminList=adminService.findAll();
        model.addAttribute("adminList",adminList);
        model.addAttribute("houseId",houseId);
        return "houseBroker/create";
    }

    @PostMapping("save")
    public String save(HouseBroker houseBroker){
        //获取经纪人信息
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBroker.setBrokerName(admin.getName());
        houseBrokerService.save(houseBroker);
        return "common/successPage";
    }

    @GetMapping("edit/{id}")
    public String edit(@PathVariable Long id,Model model){
        HouseBroker houseBroker = houseBrokerService.getById(id);
        model.addAttribute("houseBroker",houseBroker);
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);
        return "houseBroker/edit";
    }

    @PostMapping("update")
    public String update(HouseBroker houseBroker){
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.update(houseBroker);
        return "common/successPage";
    }

    @GetMapping("delete/{houseId}/{id}")
    public String remove(@PathVariable Long houseId,@PathVariable Long id){
        houseBrokerService.remove(id);
        return "redirect:/house/"+houseId;
    }
}
